package gemini.castor.ui.client.page.widget.date;

import gemini.castor.ui.client.constants.I18nConstants;
import gemini.castor.ui.client.utils.GuiUtils;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;

public class DateWidget extends Composite {

	@UiTemplate("DateWidget.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, DateWidget> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	private I18nConstants constants;

	@UiField
	ListBox lbxDay;

	@UiField
	ListBox lbxMonth;

	@UiField
	ListBox lbxYear;

	public DateWidget() {
		initWidget(binder.createAndBindUi(this));
		constants = GWT.create(I18nConstants.class);
		initData(false);
	}
	
	public DateWidget(boolean isNew) {
		initWidget(binder.createAndBindUi(this));
		constants = GWT.create(I18nConstants.class);
		initData(isNew);
	}

	@SuppressWarnings("deprecation")
	public void initData(boolean isNew) {
		for (int i = 1; i <= 31; ++i) {
			if (i < 10) {
				lbxDay.addItem("0" + String.valueOf(i), "0" + String.valueOf(i));
			} else {
				lbxDay.addItem(String.valueOf(i), String.valueOf(i));
			}
		}

		String month[] = (constants.stringMonth()).split(",");
		for (String item : month) {
			String[] monthValue = item.split(":");
			lbxMonth.addItem(monthValue[0], monthValue[1]);
		}

		if (!isNew) {
			int fromYear = 1900;
			Date currentDate = new Date();
			int toYear = fromYear + currentDate.getYear();
			for (int i = fromYear; i <= toYear; ++i) {
				lbxYear.addItem(String.valueOf(i), String.valueOf(i));
			}
		}else{
			int fromYear = 1900;
			Date currentDate = new Date();
			int toYear = fromYear + currentDate.getYear();
			for (int i = toYear; i <= toYear+10; ++i) {
				lbxYear.addItem(String.valueOf(i), String.valueOf(i));
			}
		}
	}

	public void reset() {
		lbxDay.setSelectedIndex(0);
		lbxMonth.setSelectedIndex(0);
		lbxYear.setSelectedIndex(0);
	}

	public Date getDateFromDateWidget() {
		String strDate = (lbxDay.getSelectedIndex() + 1) + "."
				+ (lbxMonth.getSelectedIndex() + 1) + "."
				+ lbxYear.getValue(lbxYear.getSelectedIndex());
		Date result = GuiUtils.format(strDate, GuiUtils.DD_MM_YYYY);
		return result;
	}

	public void setDate(Date date) {
		lbxDay.setSelectedIndex(date.getDate() - 1);
		lbxMonth.setSelectedIndex(date.getMonth());
		lbxYear.setSelectedIndex(date.getYear());
	}

}
